/*
 * bsp_encoder_as5047p.h
 *
 *  Created on: 2025 Apr 8
 *      Author: SFLY
 */

#ifndef XTFOCLIB_BOARD_DRIVERS_BSP_ENCODER_AS5047P_H_
#define XTFOCLIB_BOARD_DRIVERS_BSP_ENCODER_AS5047P_H_

#include "driverlib.h"
#include "device.h"

#define SPI_CS_H 1
#define SPI_CS_L 0
#define SPI_FREQ (5000000U)




#define SPI_MOTOR_BASE      (u32) & SpiaRegs
#define GPIO_MOTOR_CLK   9
#define GPIO_CONFIG_MOTOR_CLK GPIO_9_SPIA_CLK
#define GPIO_MOTOR_MOSI  8
#define GPIO_CONFIG_GPIO_MOTOR_MOSI GPIO_8_SPIA_SIMO
#define GPIO_MOTOR_MISO  17
#define GPIO_CONFIG_GPIO_MOTOR_MISO GPIO_17_SPIA_SOMI
#define GPIO_MOTOR_CS    11
#define GPIO_CONFIG_GPIO_MOTOR_CS GPIO_11_GPIO11


#define SPI_REDUCER_BASE      (u32) & SpibRegs
#define GPIO_REDUCER_CLK   28
#define GPIO_CONFIG_REDUCER_CLK GPIO_28_SPIB_CLK
#define GPIO_REDUCER_MOSI  24
#define GPIO_CONFIG_GPIO_REDUCER_MOSI GPIO_24_SPIB_SIMO
#define GPIO_REDUCER_MISO  6
#define GPIO_CONFIG_GPIO_REDUCER_MISO GPIO_6_SPIB_SOMI
#define GPIO_REDUCER_CS    32
#define GPIO_CONFIG_GPIO_REDUCER_CS GPIO_32_GPIO32

#define SPI_MOTOR_CS_H         GPIO_writePin(GPIO_MOTOR_CS,SPI_CS_H);
#define SPI_MOTOR_CS_L         GPIO_writePin(GPIO_MOTOR_CS,SPI_CS_L);

#define SPI_REDUCER_CS_H       GPIO_writePin(GPIO_REDUCER_CS,SPI_CS_H);
#define SPI_REDUCER_CS_L       GPIO_writePin(GPIO_REDUCER_CS,SPI_CS_L);


/*内容随外界变化的寄存器 可读不可写*/
#define NOP_ADDR      0x0000 //启动读取过程寄存器地址
#define ERRFL_ADDR    0x0001 //错误寄存器地址
#define PROG_ADDR     0x0003 //编程寄存器地址
#define DIAAGC_ADDR   0x3FFC //诊断和AGC寄存器地址
#define MAG_ADDR      0x3FFD //CORDIC寄存器地址
#define ANGLEUNC_ADDR 0x3FFE //无动态角度误差补偿的测量角度寄存器地址
#define ANGLECOM_ADDR 0x3FFF //带动态角度误差补偿的测量角度寄存器地址

/*配置选项寄存器 可读可写*/
#define ZPOSM         0x0016
#define ZPOSL         0x0017
#define SETTINGS1     0x0018
#define SETTINGS2     0x0019

/*读取数据命令*/
#define READ_ANGLECOM 0xFFFF
#define READ_NOP      0xC000
#define READ_ERRFL    0x4001

#define AS5047P_Check_MAG_TooLow(DIAAGC)      ((DIAAGC >> 11) & 0x0001)
#define AS5047P_Check_MAG_TooHigh(DIAAGC)     ((DIAAGC >> 10) & 0x0001)
#define AS5047P_Check_CORDIC_Overflow(DIAAGC) ((DIAAGC >> 9)  & 0x0001)
#define AS5047P_Check_LF_finished(DIAAGC)     ((DIAAGC >> 8)  & 0x0001)


void Bsp_Encoder_Init(void);
uint16_t Bsp_Encoder_SendByte(uint32_t base, uint16_t data);
void BSP_Motor_Encoder_Write(uint16_t address,uint16_t value);
uint16_t BSP_Motor_Encoder_Read(uint16_t address);
uint16_t BSP_Motor_Encoder_ReadAngle(void);
void BSP_Reducer_Encoder_Write(uint16_t address,uint16_t value);
uint16_t BSP_Reducer_Encoder_Read(uint16_t address);
uint16_t BSP_Reducer_Encoder_ReadAngle(void);


#endif /* XTFOCLIB_BOARD_DRIVERS_BSP_ENCODER_AS5047P_H_ */
